<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of MY_Model
 *
 * @author Lucas Pinheiro
 */
class MY_Model extends CI_Model {

    //put your code here
    protected $banco = null;
    protected $tabela = null;
    protected $apelido = null;

    public function __construct() {
        parent::__construct();
    }

    public function get($key, $value) {
        $this->db->where($key, $value);
        $query = $this->db->get(($this->banco != null ? $this->banco . '.' : '') . $this->tabela . ' as ' . $this->apelido);
        if ($query->num_rows() > 0) {
            return $query->row();
        } else {
            return NULL;
        }
    }

    public function get_all($key = NULL, $value = NULL, $limit_inicio = NULL, $limit_fim = NULL) {
        if ($key != NULL) {
            $this->db->where($key, $value);
        }
        $query = $this->db->get(($this->banco != null ? $this->banco . '.' : '') . $this->tabela . ' as ' . $this->apelido, $limit_inicio, $limit_fim);
        if ($query->num_rows() > 0) {
            return $query->result();
        } else {
            return NULL;
        }
    }

    public function search($key = NULL, $value = NULL, $limit_inicio = NULL, $limit_fim = NULL) {
        if ($key != NULL) {
            $this->db->like($key, $value);
        }
        $query = $this->db->get(($this->banco != null ? $this->banco . '.' : '') . $this->tabela . ' as ' . $this->apelido, $limit_inicio, $limit_fim);
        if ($query->num_rows() > 0) {
            return $query->result();
        } else {
            return NULL;
        }
    }

    public function cadastrar($dados = array()) {
        $this->db->insert(($this->banco != null ? $this->banco . '.' : '') . $this->tabela, $dados);
        if ($this->db->affected_rows() > 0) {
            return $this->db->insert_id();
        } else {
            return NULL;
        }
    }

    public function alterar($key, $value, $dados = array()) {
        $this->db->where($key, $value);
        $this->db->update(($this->banco != null ? $this->banco . '.' : '') . $this->tabela, $dados);
        if ($this->db->affected_rows() > 0) {
            return $value;
        } else {
            return NULL;
        }
    }

    public function excluir($key, $value) {
        $this->db->where($key, $value);
        $this->db->delete(($this->banco != null ? $this->banco . '.' : '') . $this->tabela);
        if ($this->db->affected_rows() > 0) {
            return TRUE;
        } else {
            return NULL;
        }
    }

    public function debug() {
        echo '<pre>';
        var_dump($this->db->last_query());
        echo '</pre>';
    }

}